package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.PublishFinishEvent;
import com.bnlr.lrparking.model.AddStallTypeBean;
import com.bnlr.lrparking.model.AlterPublishDetailBean;
import com.bnlr.lrparking.model.CarPlaceTypeMode;
import com.bnlr.lrparking.model.MyPublishBean;
import com.bnlr.lrparking.util.GlideImageLoader;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.widget.ConvertHelper;
import com.bnlr.lrparking.widget.boarddialog.InputBoardDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 发布信息填写
 * @author tian
 */
public class PublishActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.rl_image)
    RelativeLayout rlImage;
    @BindView(R.id.iv_upload)
    ImageView ivLoad;
    @BindView(R.id.ivHead)
    Banner ivHead;
    @BindView(R.id.publish_title)
    ClearEditText etTitle;
    @BindView(R.id.publish_housing)
    ClearEditText etHousing;
    @BindView(R.id.publish_park_dq)
    TextView dpChose;
    @BindView(R.id.publish_place_number)
    ClearEditText etParkNumber;
    @BindView(R.id.publish_place_floor)
    ClearEditText etParkFloor;
    @BindView(R.id.type_choose)
    TextView tvCarType;
    @BindView(R.id.et_mj)
    TextView etMj;

    private int tag;
    private List<String> imgList = new ArrayList<>();
    private List<String> fileList = new ArrayList<>();
    private String photoString = "",authPhotoString = "";

    private OptionsPickerView pvCustomOptions;
    private ArrayList<ArrayList<CarPlaceTypeMode>> carType2 = new ArrayList<>();
    private ArrayList<CarPlaceTypeMode> carType1 = new ArrayList<>();

    private String carPlaceId;
    private String mjCount = "";
    private Double lat,lng;
    private String cityName,areaName;
    private MyPublishBean.DataBean dataBean;
    /**
     * 修改  传参
     */
    private AlterPublishDetailBean.DataBean  bean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        unbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        tag = intent.getIntExtra("publish_tag",0);
        dataBean = intent.getParcelableExtra("alter_publish");
        initValue();
        switch (tag) {
            case 1:
                tvTitle.setText("发布出租车位信息");
                etTitle.setHint("突出的标题更容易将车位出租哦");
                break;
            case 2:
                tvTitle.setText("发布出售车位信息");
                etTitle.setHint("突出的标题更容易将车位出售哦");
                break;
            default:
                break;
        }
        ivHead.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(PublishActivity.this,EditStallPhotoActivity.class);
                intent.putExtra("imgList", (Serializable) imgList);
                intent.putExtra("fileList", (Serializable) fileList);
                startActivityForResult(intent,1005);
            }

        });
    }

    private void initValue() {
        if (dataBean != null) {
            try {
                mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
                mRequest.add("action", "GetEditSpaceDetail");
                mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                mRequest.add("phonePara", Application.DEVICE_ID);
                mRequest.add("parkSpaceId",dataBean.getId());
                // 添加到请求队列+
                CallServer.getRequestInstance().add(baseContext, mRequest,
                        new CustomHttpListener<AlterPublishDetailBean>(baseContext, true, AlterPublishDetailBean.class) {
                            @Override
                            public void doWork(AlterPublishDetailBean data, String code) {
                                if (code.equals("1")) {
                                    if (data.getData() != null && data.getData().get(0) != null) {
                                        bean =  data.getData().get(0);
                                        for (int i = 0; i < bean.getPhotoList().size(); i++) {
                                            imgList.add(bean.getPhotoList().get(i).getPhotoUrl());
                                        }
                                        for (int i = 0; i < bean.getAuthPhotoList().size(); i++) {
                                            fileList.add(bean.getAuthPhotoList().get(i).getPhotoUrl());
                                        }
                                        List<String> topBannerList = new ArrayList<>();
                                        topBannerList.addAll(imgList);
                                        topBannerList.addAll(fileList);
                                        ivHead.setImages(topBannerList)
                                                .setDelayTime(3000)
                                                .setImageLoader(new GlideImageLoader())
                                                .start();
                                        String photo1="";
                                        String photo2="";
                                        for (int i = 0; i < imgList.size(); i++) {
                                            photo1 = photo1 + imgList.get(i) +",";
                                        }
                                        if (!TextUtils.isEmpty(photo1)) {
                                            photoString = photo1.substring(0,photo1.length()-1);
                                        }

                                        for (int i = 0; i < fileList.size(); i++) {
                                            photo2 = photo2 + fileList.get(i) +",";
                                        }
                                        if (!TextUtils.isEmpty(photo2)) {
                                            authPhotoString = photo2.substring(0,photo2.length()-1);
                                        }

                                        etTitle.setText(ConvertHelper.convertToString(bean.getTitle()));
                                        dpChose.setText(ConvertHelper.convertToString(bean.getAddress()));
                                        lat = bean.getLatitude();
                                        lng = bean.getLongitude();
                                        etParkNumber.setText(ConvertHelper.convertToString(bean.getNumber()));
                                        etHousing.setText(bean.getParkingName());
                                        etParkFloor.setText(ConvertHelper.convertToString(bean.getFloorNum()));
                                        tvCarType.setText(ConvertHelper.convertToString(bean.getSpaceTypeString()));
                                        carPlaceId =  ConvertHelper.convertToString(bean.getSpaceType());
                                        etMj.setText(ConvertHelper.convertToString(bean.getSize()) + "㎡");
                                        mjCount = ConvertHelper.convertToString(bean.getSize());
                                        mjCount = ConvertHelper.convertToString(bean.getSize());
                                    }
                                }

                            }
                            @Override
                            public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                                if (!code.equals("1")) {
                                    CarCommon carCommon = new CarCommon();
                                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                        @Override
                                        public void setSure() {
                                            finish();
                                        }
                                    });
                                    try {
                                        carCommon.ReminderDialog(PublishActivity.this,obj.getString("msg"),"提示");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, true);
            } catch (Exception e) {

            }
        }
    }


    @OnClick({R.id.iv_back, R.id.ivHead,R.id.publish_park_dq,R.id.type_choose,R.id.et_mj,R.id.publish_next})
    public void pubOnClick (View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ivHead:
                Intent intent = new Intent(this,EditStallPhotoActivity.class);
                intent.putExtra("imgList", (Serializable) imgList);
                intent.putExtra("fileList", (Serializable) fileList);
                startActivityForResult(intent,1005);
                break;
            //地址选择
            case R.id.publish_park_dq:
                startActivityForResult(new Intent(this,SelectParkingActivity.class)
                        ,1007);
                break;
            case R.id.type_choose:
                if (carType1.size() > 0) {
                    initCustomOptionPicker();
                } else {
                    getCarPlaceType();
                }
                break;
            case R.id.et_mj:
                InputBoardDialog dialog2 = new InputBoardDialog(this,mjCount,"㎡");
                dialog2.setOnDialogResultListener(new InputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (!"cancel".equals(result)) {
                            etMj.setText(result);
                            if (result.equals("")) {
                                mjCount = "";
                            } else {
                                mjCount = result.substring(0,result.length() -1 );
                            }
                        }
                    }
                });
                dialog2.show();
                break;
            case R.id.publish_next:
                next();
                break;
            default:
                break;
        }
    }

    private void next() {
//        if (imgList.size() <= 0) {
//            ToastUtils.showShort("图片不能为空");
//            return;
//        }
//        if (fileList.size() <= 0) {
//            ToastUtils.showShort("车位相关文件不能为空");
//            return;
//        }
        String publishTitle = etTitle.getText().toString();
        if (TextUtils.isEmpty(publishTitle)) {
            ToastUtils.showShort("标题不能为空");
            return;
        }
        String house = etHousing.getText().toString();
        if (TextUtils.isEmpty(house)) {
            ToastUtils.showShort("请填写小区名称");
            return;
        }
        String parkingAddress = dpChose.getText().toString();
        if (TextUtils.isEmpty(parkingAddress)) {
            ToastUtils.showShort("请选择停车场地址");
            return;
        }
        String carNumber = etParkNumber.getText().toString();
        if (TextUtils.isEmpty(carNumber)) {
            ToastUtils.showShort("请填写车位编号");
            return;
        }
        String carFloor = etParkFloor.getText().toString();
        if (TextUtils.isEmpty(carFloor)) {
            ToastUtils.showShort("请填写车位所在楼层");
            return;
        }
        String type = tvCarType.getText().toString();
        if (TextUtils.isEmpty(type)) {
            ToastUtils.showShort("车位类型不能为空");
            return;
        }
        String mj = etMj.getText().toString();
        PublishIntentBean intentBean = new PublishIntentBean();
        intentBean.setImgString(photoString);
        intentBean.setFileString(authPhotoString);
        intentBean.setTitle(tvTitle.getText().toString());
        intentBean.setTag(tag);
        intentBean.setPublishTitle(publishTitle);
        intentBean.setAddress(parkingAddress);
        intentBean.setLatitude(lat);
        intentBean.setLongitude(lng);
        intentBean.setCityName(cityName);
        intentBean.setAreaName(areaName);
        intentBean.setCarNumber(carNumber);
        intentBean.setFloor(carFloor);
        intentBean.setHouseName(house);
        intentBean.setCarPlaceId(carPlaceId);
        intentBean.setMj(mjCount);
        if (bean != null) {
            intentBean.setAlter(true);
            intentBean.setHouseName(bean.getParkingName());
            intentBean.setSpaceBuildTime(bean.getSpaceBuildTime());
            intentBean.setIsHaveSpace(bean.getIsHaveSpace());
        } else {
            intentBean.setAlter(false);
        }
        startActivity(new Intent(this,PublishNextActivity.class)
        .putExtra("publish_data",intentBean)
        .putExtra("alter_next_publish",bean)
        );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1005 && resultCode == 1006 && data != null) {
            List<String> topBannerList = new ArrayList<>();
            imgList.clear();
            fileList.clear();
            imgList = (List<String>) data.getSerializableExtra("imgList");
            fileList = (List<String>) data.getSerializableExtra("fileList");
            String photo1="";
            String photo2="";

            if (imgList != null && imgList.size() >0) {
                topBannerList.addAll(imgList);
                for (int i = 0; i < imgList.size(); i++) {
                    photo1 = photo1 + imgList.get(i) +",";
                }
                photoString = photo1.substring(0,photo1.length()-1);
            } else {
                photoString = "";
            }
            if (fileList != null && fileList.size() >0) {
                topBannerList.addAll(fileList);
                for (int i = 0; i < fileList.size(); i++) {
                    photo2 = photo2 + fileList.get(i) +",";
                }
                authPhotoString = photo2.substring(0,photo2.length()-1);
            } else {
                authPhotoString = "";
            }

            if (topBannerList.size() > 0) {
                ivHead.setImages(topBannerList)
                        .setDelayTime(3000)
                        .setImageLoader(new GlideImageLoader())
                        .start();
            } else {
                ivHead.update(topBannerList);
            }
        } else if (requestCode == 1007 && resultCode == 1008 && data != null) {
            LatLng latLng = data.getParcelableExtra("location");
            lat = latLng.latitude;
            lng = latLng.longitude;
            cityName = data.getStringExtra("cityName");
            areaName = data.getStringExtra("areaName");
            dpChose.setText(data.getStringExtra("address"));
        }
    }
    /**
     * 获取车位类型
     */
    private void getCarPlaceType() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetSpaceType");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<AddStallTypeBean>(baseContext, true, AddStallTypeBean.class) {
                        @Override
                        public void doWork(AddStallTypeBean data, String code) {
                            if ("1".equals(code)) {
                                for (int i = 0; i < data.getData().size(); i++) {
                                    carType1.add(new CarPlaceTypeMode(data.getData().get(i).getKey()
                                            ,data.getData().get(i).getValue()));
                                    ArrayList<CarPlaceTypeMode> type1 = new ArrayList<>();
                                    for (int j = 0; j < data.getData().get(i).getData().size(); j++) {
                                        type1.add(new CarPlaceTypeMode
                                                (data.getData().get(i).getData().get(j).getKey(),data.getData().get(i).getData().get(j).getValue()));
                                    }
                                    carType2.add(type1);
                                }
                                initCustomOptionPicker();
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType1.get(options1).getValue()+"-"+carType2.get(options1).get(option2).getValue() ;
                tvCarType.setText(tx);
                carPlaceId = carType2.get(options1).get(option2).getKey() +"";
            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(carType1,carType2);//添加数据
        pvCustomOptions.show();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void SuccessEvent(PublishFinishEvent event){
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
